import Vue from 'vue'
import * as types from './actionTypes'
import * as mutationTypes from '../Mutation/mutationTypes'
import * as getterTypes from '../Getter/getterTypes'
import { getEnum } from '@/api/enum'
import { getToken, getLang, getClientConfig, socialBind, getSocialInfoByToken, setClientConfig, getButtons } from '@/api/app'
import { getMsgByIdAndName } from '@/api/message'
import { getPortals, getUserInfo, getPermissions } from '@/api/user'
import storage from '../../utils/storage'
import { isJSON } from '@/utils/util'
import { matchFormatToTimestamp, matchTimestampToFormat } from '../../utils/timezone'
import router from '@/permission'
import { Message } from 'fawkes-lib'
const actions = {

  // 登录系统,登录后初始化等相关操作统一处理
  [types.LOGIN] ({ dispatch }, portal) {
    dispatch(types.UPDATE_USER, portal).then(res => {
      if (res.status && res.data) {
        dispatch(types.INIT_WEBSOCKET)
      }
    })
  },

  //用户登录
  [types.USER_LOGIN] ({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      getToken(data).then(async res => {
        if (res.id) {
          //加载用户信息
          let result = await dispatch(types.LOADING_USER_DATA, res)
          if (result) {
            return resolve(res)
          }
        }
        reject('')
      }).catch(e => {
        reject(e)
      })
    })
  },
  //第三方登录
  [types.SOCIAL_LOGIN] ({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      getSocialInfoByToken(data).then(async res => {
        if (res) {
          if (res.userType === 1) {
            //已绑定，直接登录
            res.access_token = data
            //加载用户信息
            let result = await dispatch(types.LOADING_USER_DATA, res)
            if (!result) {
              return reject('')
            }
          }
          //返回用户类型，未绑定需跳转绑定
          return resolve(res.userType)
        }
        reject('')
      }).catch(e => {
        reject('')
      })
    })
  },
  //绑定用户
  [types.BIND_USER] ({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      socialBind(data).then(async res => {
        if (res.id) {
          //加载用户信息
          let result = await dispatch(types.LOADING_USER_DATA, res)
          if (result) {
            return resolve(res)
          }
        }
        reject('')
      }).catch(e => {
        reject(e)
      })
    })
  },
  //刷新token
  [types.REFRESH_TOKEN] ({ commit }, data) {
    return new Promise((resolve, reject) => {
      getToken(data).then(res => {
        if (res.access_token) {
          storage.set('access_token', res.access_token)
          storage.set('user', JSON.stringify(res))
          return resolve('success')
        }
        resolve('')
      }).catch(e => {
        resolve('')
      })
    })
  },
  //根据门户获取用户信息
  [types.UPDATE_USER] ({ commit, rootState }, portalId = rootState.portal.id) {
    return new Promise((resolve, reject) => {
      getUserInfo({ userName: `${storage.get('username')}`, portalId }).then(res => {
        if (res.status && res.data) {
          const user = res.data
          commit(mutationTypes.SET_USER, user)
          //水印判断
          commit(mutationTypes.SET_WATERMARK, user)
        }
        resolve(res)
      }).catch(e => resolve(e))
    })
  },
  //加载应用配置
  [types.LOADING_INIT_DATA] ({ dispatch }) {
    return new Promise((resolve, reject) => {
      Promise.all([dispatch(types.GET_CLIENT_CONFIG), dispatch(types.GET_ENUMS)]).then(res => {
        resolve(res)
      }).catch(e => resolve(e))
    })
  },
  //加载用户信息
  [types.LOADING_USER_DATA] ({ commit, rootGetters, dispatch }, data) {
    return new Promise(async (resolve, reject) => {
      //登录时，保存token
      if (data) {
        storage.set('username', data.userName)
        storage.set('user', JSON.stringify(data))
        data.access_token && storage.set('access_token', data.access_token)
      }
      //非登录页刷新,需要判断token
      if (storage.get('access_token') && 'undefined' != storage.get('access_token')) {
        let portal = ''
        //判断是否多门户
        if (rootGetters.multiPortal) {
          portal = await dispatch(types.GET_PORTALS)
          //无门户权限
          if (!portal) {
            storage.remove('access_token')
            resolve(false)
            return false
          }
        }
        // 执行系统登录
        dispatch(types.LOGIN, portal)
        // await dispatch(types.GET_BUTTONS)
      }
      resolve(true)
    }).catch(e => {
      return false
    })
  },

  //获取CLIENTINFO，包含通用配置、安全策略、服务器配置
  [types.GET_CLIENT_CONFIG] ({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getClientConfig().then(res => {
        if (res.status && res.data) {
          commit(mutationTypes.SET_CLIENT_CONFIG, { ...res.data })
          dispatch(types.GET_LANGS)
        }
        resolve(res)
      }).catch(err => resolve(err))
    })
  },
  // 统一修改配置的方法
  [types.PUT_CLIENT_CONFIG] ({ commit }, data) {
    // 提交需要object类型并且时间为时间戳
    const addStr = matchFormatToTimestamp(JSON.stringify(data.additionalInformation))
    const nData = { ...data, additionalInformation: JSON.parse(addStr) }
    return setClientConfig(nData).then(res => {
      if (res.status) {
        // 更新本地配置直接用object类型非时间戳
        commit(mutationTypes.SET_CLIENT_CONFIG, data)
      }
      return res
    }).catch(() => { })
  },
  //获取LATEST_CLIENT_CONFIG
  [types.GET_LATEST_CLIENT_CONFIG] ({ commit }) {
    return getClientConfig().then(res => {
      if (res.status && res.data) {
        // 对时间戳进行解析
        let additionalInformation = JSON.parse(matchTimestampToFormat(res.data.additionalInformation))
        commit(mutationTypes.SET_LATEST_CLIENT_CONFIG, { ...res.data, additionalInformation })
      }
      return res
    }).catch(() => { })
  },

  //获取语种
  [types.GET_LANGS] ({ commit, rootState, rootGetters }) {
    return new Promise((resolve, reject) => {
      if (!rootGetters.i18n || !rootState.enum.languages) {
        return resolve(0)
      }
      resolve(rootState.enum.languages)
    })
  },

  //获取语言资源
  [types.GET_LANG] ({ commit }, lang_config) {
    getLang(lang_config).then(res => {
      if (res.status && res.data) {
        commit(mutationTypes.SET_ONLINE_LANG, { ...res.data })
      }
    }).catch(() => { })

  },
  //获取枚举列表
  [types.GET_ENUMS] ({ commit }) {
    return new Promise((resolve, reject) => {
      getEnum().then(res => {
        if (res.status && res.data) {
          commit(mutationTypes.SET_ENUM, res.data)
        }
        resolve(res)
      }).catch(err => resolve(err))
    })
  },
  //获取枚举
  [types.GET_ENUM] ({ commit }, code) {
    return new Promise((resolve, reject) => {
      getEnum(code).then(res => {
        if (res.status && res.data) {
          commit(mutationTypes.SET_ENUM, res.data)
        }
      }).catch(() => { })
    })
  },

  [types.GET_BUTTONS] ({ state, commit }) {
    //获取菜单下按钮权限
    return new Promise((resolve, reject) => {
      getButtons({ type: state.portal.type }).then(res => {
        if (res.status) {
          commit(mutationTypes.SET_BUTTONS, res.data)
        }
        resolve(true)
      }).catch(() => {
        resolve(true)
      })
    })
  },

  [types.GET_PERMISSIONS] ({ state, commit }, menuId) {
    //获取按钮权限
    return new Promise((resolve, reject) => {
      getPermissions(menuId).then(res => {
        if (res.status) {
          commit(mutationTypes.SET_PERMISSION, { key: menuId, value: res.data })
        }
        resolve(true)
      }).catch(() => {
        resolve(true)
      })
    })
  },

  //获取门户
  [types.GET_PORTALS] ({ state, commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getPortals().then(res => {
        let portal = ''
        if (res.data instanceof Array && res.data.length > 0) {
          let portals = res.data.sort((f, b) => {
            return f.type - b.type
          })
          commit(mutationTypes.SET_PORTALS, portals)

          if (isJSON(`${storage.get('portal')}`)) {
            portal = portals.find(p => {
              return JSON.parse(`${storage.get('portal')}`).id === p.id
            })
          }

          !portal && (portal = portals[0])

          dispatch(types.CHANGE_PORTAL, portal)
        } else {
          Message({
            type: 'warning',
            message: state.language.Global.NO_PORTAL_PERMISSION
          })
          router.replace('/login')
        }
        resolve(portal.id || '')
      }).catch(err => resolve(''))
    })
  },
  //门户切换
  [types.CHANGE_PORTAL] ({ commit }, portal) {
    commit(mutationTypes.CLEAN_VIEWS)
    commit(mutationTypes.CLEAN_ROUTE)
    commit(mutationTypes.CLEAN_PERMISSION)
    commit(mutationTypes.CLEAN_PERMISSION_QUEUE)
    commit(mutationTypes.UPDATE_PORTAL, portal)
  },
  [types.CLEAN_DATA] ({ commit }) {
    commit(mutationTypes.CLEAN_VIEWS)
    commit(mutationTypes.CLEAN_ROUTE)
    commit(mutationTypes.CLEAN_PERMISSION)
    commit(mutationTypes.SET_PORTALS, [])
    commit(mutationTypes.CLEAN_PERMISSION_QUEUE)
    commit(mutationTypes.CLEAN_STORAGE)
  },
  //通用配置部分
  [types.TOGGLE_SIDEBAR] ({ commit }, opened) {
    commit(mutationTypes.TOGGLE_SIDEBAR, opened)
  },
  [types.CLOSE_SIDEBAR] ({ commit }, { withoutAnimation }) {
    commit(mutationTypes.CLOSE_SIDEBAR, withoutAnimation)
  },
  [types.TOGGLE_DEVICE] ({ commit }, device) {
    commit(mutationTypes.TOGGLE_DEVICE, device)
  },
  [types.CHANGE_INTERFACE] ({ commit }, data) {
    commit(mutationTypes.CHANGE_INTERFACE, data)
  },
  [types.CHANGE_WATERMARK] ({ commit }, data) {
    commit(mutationTypes.CHANGE_WATERMARK, data)
  },
  //标签栏部分
  [types.ADD_VIEW] ({ dispatch }, view) {
    dispatch(types.ADD_VISITED_VIEW, view)
    dispatch(types.ADD_CACHED_VIEW, view)
  },
  [types.ADD_VISITED_VIEW] ({ commit }, view) {
    commit(mutationTypes.ADD_VISITED_VIEW, view)
  },
  [types.ADD_CACHED_VIEW] ({ commit }, view) {
    commit(mutationTypes.ADD_CACHED_VIEW, view)
  },

  [types.DEL_VIEW] ({ dispatch, state }, view) {
    return new Promise(resolve => {
      dispatch(types.DEL_VISITED_VIEW, view)
      dispatch(types.DEL_CACHED_VIEW, view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  [types.DEL_VISITED_VIEW] ({ commit, state }, view) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_VISITED_VIEW, view)
      resolve([...state.visitedViews])
    })
  },
  [types.DEL_CACHED_VIEW] ({ commit, state }, view) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_CACHED_VIEW, view)
      resolve([...state.cachedViews])
    })
  },

  [types.DEL_OTHERS_VIEWS] ({ dispatch, state }, view) {
    return new Promise(resolve => {
      dispatch(types.DEL_OTHERS_VISITED_VIEWS, view)
      dispatch(types.DEL_OTHERS_CACHED_VIEWS, view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  [types.DEL_OTHERS_VISITED_VIEWS] ({ commit, state }, view) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_OTHERS_VISITED_VIEWS, view)
      resolve([...state.visitedViews])
    })
  },
  [types.DEL_OTHERS_CACHED_VIEWS] ({ commit, state }, view) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_OTHERS_CACHED_VIEWS, view)
      resolve([...state.cachedViews])
    })
  },

  [types.DEL_ALL_VIEWS] ({ dispatch, state }, view) {
    return new Promise(resolve => {
      dispatch(types.DEL_ALL_VISITED_VIEWS, view)
      dispatch(types.DEL_ALL_CACHED_VIEWS, view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  [types.DEL_ALL_VISITED_VIEWS] ({ commit, state }) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_ALL_VISITED_VIEWS)
      resolve([...state.visitedViews])
    })
  },
  [types.DEL_ALL_CACHED_VIEWS] ({ commit, state }) {
    return new Promise(resolve => {
      commit(mutationTypes.DEL_ALL_CACHED_VIEWS)
      resolve([...state.cachedViews])
    })
  },
  [types.UPDATE_VISITED_VIEW] ({ commit }, view) {
    commit(mutationTypes.UPDATE_VISITED_VIEW, view)
  },
  // 初始化websocket
  [types.INIT_WEBSOCKET] ({ commit, getters }) {
    if (getters[getterTypes.REAL_TIME_PUSH]) {
      Vue.prototype.$FksWebsocket({
        name: 'fks-default-websocket',
        connectType: getters[getterTypes.SOCKET_TYPE], //'stomp'
        url: Vue.prototype.VUE_APP_SOCKET_API,
        destination: '/topic/message',
        maxReconnect: getters[getterTypes.MAX_RECONNECT],
        onNewMessage: () => {
          commit(mutationTypes.UPDATE_RECEIVED_MESSAGE, true)
        }
      })

    }
  },
  /**
   * @description: 检查是否有未读消息
   */
  [types.CHECK_UNREAD_MESSAGE] ({ commit, state }) {
    return new Promise((resolve, reject) => {
      let data = {
        currentPage: 1,
        pageSize: 1,
        clientId: state.user.clientId,
        userName: state.user.userName,
        status: -1
      }
      getMsgByIdAndName(data).then(res => {
        if (res.status) {
          if (res.data.list.length > 0) {
            commit(mutationTypes.UPDATE_HAS_UNREAD_MESSAGE, true)
          } else {
            commit(mutationTypes.UPDATE_HAS_UNREAD_MESSAGE, false)
          }
          resolve(res)
        }
        reject('')
      }).catch(e => {
        reject(e)
      })
    })
  },
}

export default actions